import { NextRequest } from 'next/server';
import { cookies } from 'next/headers';
import { getUserManagement, UserWithRole } from '@/lib/user-management';

export interface AuthResult {
  success: boolean;
  user?: UserWithRole;
  error?: string;
  status?: number;
}

/**
 * 验证用户认证状态
 */
export async function verifyAuth(): Promise<AuthResult> {
  try {
    const cookieStore = await cookies();
    const sessionToken = cookieStore.get('session_token')?.value;

    if (!sessionToken) {
      return {
        success: false,
        error: '未登录',
        status: 401
      };
    }

    const userMgmt = getUserManagement();
    const user = userMgmt.validateSession(sessionToken);

    if (!user) {
      return {
        success: false,
        error: '会话已过期',
        status: 401
      };
    }

    return {
      success: true,
      user
    };
  } catch (error) {
    console.error('认证验证失败:', error);
    return {
      success: false,
      error: '认证验证失败',
      status: 500
    };
  }
}

/**
 * 验证管理员权限
 */
export async function verifyAdminAuth(): Promise<AuthResult> {
  const authResult = await verifyAuth();
  
  if (!authResult.success || !authResult.user) {
    return authResult;
  }

  const userMgmt = getUserManagement();
  const permissions = userMgmt.parseRolePermissions(authResult.user.role_permissions);

  if (!permissions.canManageUsers && !permissions.canManageRoles) {
    return {
      success: false,
      error: '权限不足',
      status: 403
    };
  }

  return authResult;
}

/**
 * 检查用户是否有权限编辑特定字段
 */
export async function verifyFieldEditPermission(
  tableName: string, 
  fieldName: string, 
  dataSource: string
): Promise<AuthResult & { canEdit?: boolean }> {
  const authResult = await verifyAuth();
  
  if (!authResult.success || !authResult.user) {
    return authResult;
  }

  const userMgmt = getUserManagement();
  const canEdit = userMgmt.canUserEditField(
    authResult.user, 
    tableName, 
    fieldName, 
    dataSource
  );

  return {
    ...authResult,
    canEdit
  };
}

/**
 * 获取用户可编辑的字段列表
 */
export async function getUserEditableFields(tableName: string): Promise<{
  success: boolean;
  fields?: string[];
  user?: UserWithRole;
  error?: string;
  status?: number;
}> {
  const authResult = await verifyAuth();
  
  if (!authResult.success || !authResult.user) {
    return authResult;
  }

  const userMgmt = getUserManagement();
  const fields = userMgmt.getUserEditableFields(authResult.user, tableName);

  return {
    success: true,
    fields,
    user: authResult.user
  };
}

/**
 * 检查用户是否有数据来源访问权限
 */
export async function verifyDataSourceAccess(dataSource: string): Promise<AuthResult & { hasAccess?: boolean }> {
  const authResult = await verifyAuth();
  
  if (!authResult.success || !authResult.user) {
    return authResult;
  }

  const userMgmt = getUserManagement();
  const permissions = userMgmt.parseRolePermissions(authResult.user.role_permissions);
  
  const hasAccess = permissions.canEditAll || permissions.dataSourceAccess.includes(dataSource);

  return {
    ...authResult,
    hasAccess
  };
}

/**
 * 验证用户是否有删除权限
 */
export async function verifyDeletePermission(): Promise<AuthResult & { canDelete?: boolean }> {
  const authResult = await verifyAuth();
  
  if (!authResult.success || !authResult.user) {
    return authResult;
  }

  const userMgmt = getUserManagement();
  const permissions = userMgmt.parseRolePermissions(authResult.user.role_permissions);
  
  // 只有管理员和有编辑权限的用户可以删除
  const canDelete = permissions.canEditAll || permissions.canManageUsers;

  return {
    ...authResult,
    canDelete
  };
}

/**
 * 验证用户是否有创建权限
 */
export async function verifyCreatePermission(): Promise<AuthResult & { canCreate?: boolean }> {
  const authResult = await verifyAuth();
  
  if (!authResult.success || !authResult.user) {
    return authResult;
  }

  const userMgmt = getUserManagement();
  const permissions = userMgmt.parseRolePermissions(authResult.user.role_permissions);
  
  // 有数据来源访问权限的用户可以创建相应的设备实例
  const canCreate = permissions.canEditAll || permissions.dataSourceAccess.length > 0;

  return {
    ...authResult,
    canCreate
  };
}

/**
 * 从请求中提取用户信息（用于客户端组件）
 */
export async function getCurrentUser(): Promise<{
  success: boolean;
  user?: UserWithRole;
  permissions?: any;
  error?: string;
}> {
  const authResult = await verifyAuth();
  
  if (!authResult.success || !authResult.user) {
    return {
      success: false,
      error: authResult.error
    };
  }

  const userMgmt = getUserManagement();
  const permissions = userMgmt.parseRolePermissions(authResult.user.role_permissions);

  return {
    success: true,
    user: authResult.user,
    permissions
  };
}
